package com.leetroll.app.controller;

import com.leetroll.api.service.CartService;
import com.leetroll.app.utils.AppJwtTokenUtil;
import com.leetroll.common.bean.ApiResponse;
import com.leetroll.common.entity.Cart;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;


@RestController
@RequestMapping("/cart")
@Api(value = "购物车相关接口", tags = {"购物车相关接口"})
@Slf4j
public class CartController {
    private final CartService cartService;
    private final AppJwtTokenUtil jwtTokenUtil;
    @Autowired
    public CartController(CartService cartService, AppJwtTokenUtil jwtTokenUtil) {
        this.cartService = cartService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @ApiOperation(value = "购物车资源", notes = "购物车资源")
    @GetMapping("/list")
    public ApiResponse<?> list(HttpServletRequest request) {
        Long userId = jwtTokenUtil.getUserId(request);
        if (userId == null) return ApiResponse.OK(Collections.EMPTY_LIST);
        return ApiResponse.OK(cartService.listByUserId(userId));
    }

    @ApiOperation(value = "购物车资源", notes = "购物车资源")
    @GetMapping("/page")
    public ApiResponse<?> page(HttpServletRequest request,
                               @RequestParam(name = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
                               @RequestParam(name = "pageSize", required = false, defaultValue = "12") Integer pageSize) {
        Long userId = jwtTokenUtil.getUserId(request);
        if (userId == null) return ApiResponse.OK(Collections.EMPTY_LIST);
        return ApiResponse.OK(cartService.pageByUserId(userId, pageNumber, pageSize));
    }


    @ApiOperation(value = "购物车数量", notes = "购物车数量")
    @GetMapping("/count")
    public ApiResponse<Integer> getItemsCount(HttpServletRequest request) {
        Long userId = jwtTokenUtil.getUserId(request);
        if (userId == null) return ApiResponse.OK(0);
        return ApiResponse.OK(cartService.listByUserId(userId).size());
    }

    @ApiOperation(value = "加入购物车", notes = "加入购物车")
    @GetMapping("/add/{itemId}")
    public ApiResponse<?> add(HttpServletRequest request,  @PathVariable Long itemId) {
        Long userId = jwtTokenUtil.getUserId(request);
        Cart cart = new Cart(userId, itemId);
        boolean exist = cartService.exist(cart);
        if (exist) return ApiResponse.OK();

        cart.insert();
        return ApiResponse.OK();
    }

    @ApiOperation(value = "删除购物车条目", notes = "删除购物车条目")
    @GetMapping("/del/{id}")
    public ApiResponse<?> delItem(@PathVariable Integer id) {
        if (id == null) return ApiResponse.OK();
        cartService.removeById(id);
        return ApiResponse.OK();
    }
}
